package com.kanshu.ksgb.fastread.doudou.common.business.manager;

import android.annotation.TargetApi;
import android.os.Build;
import android.text.TextUtils;

import com.kanshu.ksgb.fastread.doudou.app.Xutils;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.UserUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.FileUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.ThreadPoolUtil;

import java.io.File;

import static com.kanshu.ksgb.fastread.doudou.common.util.FileUtils.createFile;


/**
 * Created by wcy on 2017\7\3 0003.
 */

public class CacheManager {

    private static CacheManager manager;
    // 阅读器缓存路径
    private String pathData;
    private String pathDataTxt;
    private boolean canCache = true;

    public static CacheManager getInstance() {
        if (manager == null) {
            synchronized (CacheManager.class) {
                if (manager == null) {
                    manager = new CacheManager();
                }
            }
        }
        return manager;
    }

    public File getChapterFile(String bookId, int chapter) {
        File file = getCurChapterFile(bookId, chapter);
        if (file != null && file.length() > 5)
            return file;
        file = getCurDownloadChapterFile(bookId, chapter);
        if (file != null && file.length() > 5)
            return file;
        return null;
    }

    public File getDownloadChapterFile(String bookId, int chapter) {
        File file = getCurDownloadChapterFile(bookId, chapter);
        if (file != null && file.length() > 5)
            return file;
        return null;
    }

    /**
     * 正常缓存的文件
     * @param bookId
     * @param chapter
     * @return
     */
    public static String getChapterPath(String bookId, int chapter) {
        return CacheManager.getInstance().getPathDataTxt() + bookId + File.separator + chapter + ".txt";
    }

    /**
     * 下载的缓存文件
     * @param bookId
     * @param chapter
     * @return
     */
    public static String getDownloadChapterPath(String bookId, int chapter) {
        return CacheManager.getInstance().getPathDataTxt() + bookId + File.separator + chapter + "_download.txt";
    }

    /**
     * 得到正常的下载章节文件
     * @param bookId
     * @param chapter
     * @return
     */
    public static File getCurChapterFile(String bookId, int chapter) {
        File file = new File(getChapterPath(bookId, chapter));
        if (!file.exists())
            createFile(file);
        return file;
    }

    public static File getCurDownloadChapterFile(String bookId, int chapter) {
        File file = new File(getDownloadChapterPath(bookId, chapter));
        if (!file.exists())
            createFile(file);
        return file;
    }

    public void setCanCache(boolean canCache) {
        this.canCache = canCache;
    }

    public boolean isCanCache() {
        return canCache;
    }

    /**
     * 保存缓存文件
     * @param bookId
     * @param chapter
     * @param data
     */
    public void saveChapterFile(String bookId, int chapter, String data) {
        File file = getCurChapterFile(bookId, chapter);
        FileUtils.writeFile(file.getAbsolutePath(), data, false);
    }

    public void saveDownloadChapterFile(String bookId, int chapter , String data) {
        File file = getCurDownloadChapterFile(bookId, chapter);
        FileUtils.writeFile(file.getAbsolutePath(), data, false);
    }

    /**
     * 获取缓存大小
     *
     * @return
     */
    @TargetApi(Build.VERSION_CODES.FROYO)
    public synchronized String getCacheSize() {
        long cacheSize = 0;
        try {
            File cacheDir = Xutils.getContext().getCacheDir();
            cacheSize += FileUtils.getFolderSize(cacheDir);
            if (FileUtils.isSdCardAvailable()) {
                File extCacheDir = Xutils.getContext().getExternalCacheDir();
                cacheSize += FileUtils.getFolderSize(extCacheDir);
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
        return FileUtils.getFormatSize(cacheSize);
    }

    /**
     * 获取书籍下载内容大小
     *
     * @return
     */
    @TargetApi(Build.VERSION_CODES.FROYO)
    public synchronized long getBookDownloadSize(String bookId) {
        long cacheSize = 0;
        try {
            File bookDownload = new File(getPathDataTxt() + bookId);
            cacheSize += FileUtils.getDownloadSize(bookDownload);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return cacheSize;
    }

    /**
     * 获取书籍下载章节数量
     *
     * @return
     */
    @TargetApi(Build.VERSION_CODES.FROYO)
    public synchronized int getBookDownloadNum(String bookId) {
        int result = 0;
        try {
            File bookDownload = new File(getPathDataTxt() + bookId);
            bookDownload.listFiles();
            File[] fileList = bookDownload.listFiles();
            if (fileList == null) {
                return result;
            }
            for (File aFileList : fileList) {
                if (aFileList.length() > 5 && aFileList.getPath().endsWith("download.txt")) {
                    result += 1;
                }
            }
            return result;
        } catch (Exception e) {
            e.printStackTrace();
        }
        return result;
    }

    /**
     * 清除缓存
     *
     * @param clearReadPos 是否删除阅读记录
     */
    public synchronized void clearCache(boolean clearReadPos, boolean clearCollect) {
        try {
            // 删除内存缓存
            String cacheDir = Xutils.getContext().getCacheDir().getPath();
            FileUtils.deleteFolderFile(cacheDir, true);
            if (FileUtils.isSdCardAvailable()) {
                // 删除SD书籍缓存
                FileUtils.deleteFolderFile(CacheManager.getInstance().getPathData(), true);
            }
            // 删除阅读记录（SharePreference）
            if (clearReadPos) {
                //防止再次弹出性别选择框，sp要重写入保存的性别
            }
            // 清空书架
            if (clearCollect) {
            }
            // 清除其他缓存
            //ACache.get(Xutils.getContext()).clear();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


    public void deleteFile(final String path) {
        ThreadPoolUtil.getInstance().addTask(new Runnable() {
            @Override
            public void run() {
                File file = new File(path);
                if (file.exists()) {
                    if(file.delete()) {
                    }
                }
            }
        });

    }

    public String getPathData() {
        if (TextUtils.isEmpty(pathData)) {
            pathData = FileUtils.createRootPath(Xutils.getContext()) + "/cache";
        }
        return pathData;
    }

    public String getPathDataTxt() {
        // 免费版本（默认是付费版本）
        String bookDir = "/book/";
        // 3.0.8版本加入了userid套在外层
        String userIdDir = "";
        if (!TextUtils.isEmpty(UserUtils.getUserId())) {
            userIdDir = UserUtils.getUserId() + "/";
        }
        return getPathData() + bookDir + userIdDir;
    }


}
